<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">



  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico?v=5.1.4">






  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="3.1 关于用户的思考 不管是网站也好，还是API也好，我们都逃脱不了用户这个概念，我们下面就要来讨论用户的相关操作  对于用户而言，第一件事情，我们就要完成用户注册的操作，说到注册用户，我们想到，可以在视图函数文件中增加一个注册用户的视图函数–create_user，并且我们会在其中接受账号和密码，来完成用户的注册，这个逻辑是通常意义上的用户的概念。  普通用户：使用鱼书的人相对于鱼书来说，就是">
<meta property="og:type" content="article">
<meta property="og:title" content="Flask构建可扩展的RESTful-API-3--自定义异常对象">
<meta property="og:url" content="http://imwl.ml/flask-api/Flask构建可扩展的RESTful-API-3--自定义异常对象/index.html">
<meta property="og:site_name" content="Get busy living">
<meta property="og:description" content="3.1 关于用户的思考 不管是网站也好，还是API也好，我们都逃脱不了用户这个概念，我们下面就要来讨论用户的相关操作  对于用户而言，第一件事情，我们就要完成用户注册的操作，说到注册用户，我们想到，可以在视图函数文件中增加一个注册用户的视图函数–create_user，并且我们会在其中接受账号和密码，来完成用户的注册，这个逻辑是通常意义上的用户的概念。  普通用户：使用鱼书的人相对于鱼书来说，就是">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-04-14T14:46:34.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Flask构建可扩展的RESTful-API-3--自定义异常对象">
<meta name="twitter:description" content="3.1 关于用户的思考 不管是网站也好，还是API也好，我们都逃脱不了用户这个概念，我们下面就要来讨论用户的相关操作  对于用户而言，第一件事情，我们就要完成用户注册的操作，说到注册用户，我们想到，可以在视图函数文件中增加一个注册用户的视图函数–create_user，并且我们会在其中接受账号和密码，来完成用户的注册，这个逻辑是通常意义上的用户的概念。  普通用户：使用鱼书的人相对于鱼书来说，就是">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://imwl.ml/flask-api/Flask构建可扩展的RESTful-API-3--自定义异常对象/">





  <title>Flask构建可扩展的RESTful-API-3--自定义异常对象 | Get busy living</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>
	

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Get busy living</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Stay Hungry,Stay Foolish</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-gitbook">
          <a href="/book/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br>
            
            gitbook
          </a>
        </li>
      
        
        <li class="menu-item menu-item-resume">
          <a href="/resume/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-address-card"></i> <br>
            
            个人简历
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://imwl.ml/flask-api/Flask构建可扩展的RESTful-API-3--自定义异常对象/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="WeiLai">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Get busy living">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Flask构建可扩展的RESTful-API-3--自定义异常对象</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-12-18T18:36:16+08:00">
                2018-12-18
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/flask-api/" itemprop="url" rel="index">
                    <span itemprop="name">flask-api</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="3-1-关于用户的思考"><a href="#3-1-关于用户的思考" class="headerlink" title="3.1 关于用户的思考"></a>3.1 关于用户的思考</h1><p> 不管是网站也好，还是API也好，我们都逃脱不了用户这个概念，我们下面就要来讨论用户的相关操作</p>
<p> 对于用户而言，第一件事情，我们就要完成用户注册的操作，说到注册用户，我们想到，可以在视图函数文件中增加一个注册用户的视图函数–create_user，并且我们会在其中接受账号和密码，来完成用户的注册，这个逻辑是通常意义上的用户的概念。</p>
<p> 普通用户：使用鱼书的人相对于鱼书来说，就是用户；我们相对于QQ和微信，也是他的用户。</p>
<p> 但是我们在做API的时候，不能只考虑这些普通意义的用户，我们还要考虑一些特别的用户。例如：我们开发了一个向外提供数据的API，加入有一天，有一个公司，想使用我们的API开发他们自己的产品（小程序或者APP），这些其他的客户端，都是我们API的用户</p>
<p>根据以上的分析，我们可以得出几个结论：<br>对于API而言，再叫做用户就不太合适 ，我们更倾向于把人，第三方的产品等同于成为客户端（client）来代替User。<br>客户端的种类非常多，注册的形式就非常多。如对于普通的用户而言，就是账号和密码，但是账号和密码又可以分成，短信，邮件，社交用户。对于多种的注册形式，也不是所有的都需要密码，如小程序就不需要。<br>API和普通的业务系统是不一样的，他具有开发性和通用性。<br>因为注册的形式就非常多，所以我们不可能用万能的方式来解决。如果我们不能很好的处理多种多样的形式，我们的代码就会非常的杂乱</p>
<p>3.2 注册client<br>对于登录/注册这些比较重要的接口，我们建议提供一个统一的调用接口，而不应该拆分成多个。</p>
<p>我们可以编写一个枚举类，来枚举所有的客户端类型。<br>app\libs\enums.py<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">from enum import Enum</span><br><span class="line"></span><br><span class="line"># 定义一个枚举</span><br><span class="line">class ClientTypeEnum(Enum):</span><br><span class="line">    USER_EMAIL =  100</span><br><span class="line">    USER_MOBILE = 101</span><br><span class="line"></span><br><span class="line">    # 微信小程序</span><br><span class="line">    USER_MINA = 200</span><br><span class="line">    #微信公众号</span><br><span class="line">    UESR_WX = 201</span><br></pre></td></tr></table></figure></p>
<p>1.构建client验证器<br>app\validators\forms.py<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">from wtforms import Form, StringField, IntegerField    # 字符串类型,数字类型</span><br><span class="line">from wtforms.validators import DataRequired, length</span><br><span class="line">from app.libs.enums import ClientTypeEnum</span><br><span class="line"></span><br><span class="line"># 构建client验证器</span><br><span class="line">class ClientForm(Form):</span><br><span class="line">    account = StringField(validators=[DataRequired(), length(min=1, max=32)])</span><br><span class="line">    secret = StringField()   # 由于客户端类型的不同，密码不一定要传入</span><br><span class="line">    type = IntegerField(validators=[DataRequired()])</span><br><span class="line"></span><br><span class="line">    # 验证client_type</span><br><span class="line">    def validate_type(self, value):</span><br><span class="line">        try:</span><br><span class="line">        # 将用户传来的参数去枚举类中匹配，如果匹配失败，则抛出异常</span><br><span class="line">        # 如果匹配成功则将int转换成枚举</span><br><span class="line">            client = ClientTypeEnum(value.data)  # value.data 取到值</span><br><span class="line">        except ValueError as e:</span><br><span class="line">            raise e</span><br></pre></td></tr></table></figure></p>
<p>2.处理不同客户端注册的方案<br>由于python没有switch-case，我们可以使用dict来替换<br>app\api\v1\client.py<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">from app.libs.redprint import Redprint</span><br><span class="line"></span><br><span class="line">from app.validators.forms import ClientForm</span><br><span class="line">from flask import request</span><br><span class="line">from app.libs.enums import ClientTypeEnum</span><br><span class="line"></span><br><span class="line">api = Redprint(&apos;client&apos;)  # 实例化一个Redprint</span><br><span class="line"></span><br><span class="line">@api.route(&apos;/register&apos;, methods = [&apos;PSOT&apos;] )  # 路由注册</span><br><span class="line">def create_client():</span><br><span class="line">    # 表单 - 一般网页  json - 一般移动端</span><br><span class="line">    # 注册 登录</span><br><span class="line">    # 参数 校验  接收参数</span><br><span class="line">    # WTForms 验证表单</span><br><span class="line"></span><br><span class="line">#用来接收json类型的参数</span><br><span class="line">    data = request.json</span><br><span class="line"># 关键字参数data是wtform中用来接收json参数的方法</span><br><span class="line">    form = ClientForm(data=data)</span><br><span class="line"></span><br><span class="line">    if form.validate():</span><br><span class="line"># 替代switchcase-&#123;Enum_name:handle_func&#125;</span><br><span class="line">        promise = &#123;</span><br><span class="line">            ClientTypeEnum.USER_EMAIL: __register_user_by_email#,</span><br><span class="line">            # ClientTypeEnum.USER_MINA: __register_user_by_MINA   # 可在此处构建多种枚举类型</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">def __register_user_by_email():</span><br><span class="line">    pass</span><br><span class="line"></span><br><span class="line"># def __register_user_by_MINA():</span><br><span class="line">#     pass</span><br></pre></td></tr></table></figure></p>
<p>3.用户模型的设计<br>app\models\base.py</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line">from datetime import datetime</span><br><span class="line"></span><br><span class="line">from flask_sqlalchemy import SQLAlchemy as _SQLAlchemy, BaseQuery</span><br><span class="line">from sqlalchemy import Column, Integer, SmallInteger</span><br><span class="line">from contextlib import contextmanager</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class SQLAlchemy(_SQLAlchemy):</span><br><span class="line">    @contextmanager</span><br><span class="line">    def auto_commit(self):</span><br><span class="line">        try:</span><br><span class="line">            yield</span><br><span class="line">            self.session.commit()</span><br><span class="line">        except Exception as e:</span><br><span class="line">            db.session.rollback()</span><br><span class="line">            raise e</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class Query(BaseQuery):</span><br><span class="line">    def filter_by(self, **kwargs):</span><br><span class="line">        if &apos;status&apos; not in kwargs.keys():</span><br><span class="line">            kwargs[&apos;status&apos;] = 1</span><br><span class="line">        return super(Query, self).filter_by(**kwargs)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">db = SQLAlchemy(query_class=Query)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class Base(db.Model):</span><br><span class="line">    __abstract__ = True</span><br><span class="line">    create_time = Column(Integer)</span><br><span class="line">    status = Column(SmallInteger, default=1)</span><br><span class="line"></span><br><span class="line">    def __init__(self):</span><br><span class="line">        self.create_time = int(datetime.now().timestamp())</span><br><span class="line"></span><br><span class="line">    @property</span><br><span class="line">    def create_datetime(self):</span><br><span class="line">        if self.create_time:</span><br><span class="line">            return datetime.fromtimestamp(self.create_time)</span><br><span class="line">        else:</span><br><span class="line">            return None</span><br><span class="line"></span><br><span class="line">    def set_attrs(self, attrs_dict):</span><br><span class="line">        for key, value in attrs_dict.items():</span><br><span class="line">            if hasattr(self, key) and key != &apos;id&apos;:</span><br><span class="line">                setattr(self, key, value)</span><br><span class="line"></span><br><span class="line">    def delete(self):</span><br><span class="line">        self.status = 0</span><br></pre></td></tr></table></figure>
<p>app\models\user.py</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">from sqlalchemy import inspect, Column, Integer, String, SmallInteger, orm</span><br><span class="line">from werkzeug.security import generate_password_hash, check_password_hash</span><br><span class="line"></span><br><span class="line"># from app.libs.error_code import NotFound, AuthFailed</span><br><span class="line">from app.models.base import Base</span><br><span class="line">import datetime</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class User(Base):</span><br><span class="line">    id = Column(Integer, primary_key=True)</span><br><span class="line">    email = Column(String(24), unique=True, nullable=False)</span><br><span class="line">    nickname = Column(String(24), unique=True)</span><br><span class="line">    auth = Column(SmallInteger, default=1)   # 做层级的标志</span><br><span class="line">    _password = Column(&apos;password&apos;, String(100))</span><br><span class="line"></span><br><span class="line">    def keys(self):</span><br><span class="line">        return [&apos;id&apos;, &apos;email&apos;, &apos;nickname&apos;, &apos;auth&apos;]</span><br><span class="line"></span><br><span class="line">    @property               </span><br><span class="line">    def password(self):</span><br><span class="line">        return self._password   #  对密码的处理</span><br><span class="line"></span><br><span class="line">    @password.setter</span><br><span class="line">    def password(self, raw):</span><br><span class="line">        self._password = generate_password_hash(raw)    #  对密码的处理</span><br></pre></td></tr></table></figure>
<p>添加一个注册的方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">from sqlalchemy import inspect, Column, Integer, String, SmallInteger, orm</span><br><span class="line">from werkzeug.security import generate_password_hash, check_password_hash</span><br><span class="line"></span><br><span class="line"># from app.libs.error_code import NotFound, AuthFailed</span><br><span class="line">from app.models.base import Base , db</span><br><span class="line">import datetime</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class User(Base):</span><br><span class="line">    id = Column(Integer, primary_key=True)</span><br><span class="line">    email = Column(String(24), unique=True, nullable=False)</span><br><span class="line">    nickname = Column(String(24), unique=True)</span><br><span class="line">    auth = Column(SmallInteger, default=1)   # 做层级的标志</span><br><span class="line">    _password = Column(&apos;password&apos;, String(100))</span><br><span class="line"></span><br><span class="line">    def keys(self):</span><br><span class="line">        return [&apos;id&apos;, &apos;email&apos;, &apos;nickname&apos;, &apos;auth&apos;]</span><br><span class="line"></span><br><span class="line">    @property               </span><br><span class="line">    def password(self):</span><br><span class="line">        return self._password   #  对密码的处理</span><br><span class="line"></span><br><span class="line">    @password.setter</span><br><span class="line">    def password(self, raw):</span><br><span class="line">        self._password = generate_password_hash(raw)    #  对密码的处理</span><br><span class="line"></span><br><span class="line">    @staticmethod</span><br><span class="line">    def register_by_email(nickname, account, secret):</span><br><span class="line">        with db.auto_commit():</span><br><span class="line">            user = User()</span><br><span class="line">            user.nickname = nickname</span><br><span class="line">            user.email = account</span><br><span class="line">            user.password = secret</span><br><span class="line">            db.session.add(user)</span><br></pre></td></tr></table></figure></p>
<p>插件的注册<br>app__init__.py<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">from flask import Flask</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 将Blueprint注册到flask核心对象上,并传入一个前缀&apos;/v1&apos;</span><br><span class="line">def register_blueprints(app):</span><br><span class="line">    # from app.api.v1.user import user</span><br><span class="line">    # from app.api.v1.book import book</span><br><span class="line">    # app.register_blueprint(user)</span><br><span class="line">    # app.register_blueprint(book)</span><br><span class="line">    from app.api.v1 import create_blueprint_v1</span><br><span class="line">    app.register_blueprint(create_blueprint_v1(), url_prefix = &apos;/v1&apos;)</span><br><span class="line"></span><br><span class="line">def registe_plugin(app):  # 插件的注册</span><br><span class="line">    from app.models.base import db</span><br><span class="line">    db.init_app(app)</span><br><span class="line"></span><br><span class="line">    with app.app_context():  # 上下文环境 把app推入到上下文栈中 才能使用create_all</span><br><span class="line">        db.create_all()  # 来创建所有数据库，数据表</span><br><span class="line"></span><br><span class="line">def create_app():</span><br><span class="line">    app = Flask(__name__)   # 实例化flask核心对象</span><br><span class="line">    app.config.from_object(&apos;app.config.secure&apos;)  # 读取配置文件下的secure</span><br><span class="line">    app.config.from_object(&apos;app.config.setting&apos;) # 读取配置文件下的setting</span><br><span class="line"></span><br><span class="line">    register_blueprints(app)    # 注册蓝图到核心对象上</span><br><span class="line">    registe_plugin(app)  # 最后调用 registe_plugin</span><br><span class="line"></span><br><span class="line">    return app</span><br></pre></td></tr></table></figure></p>
<p>4.完成客户端注册<br>之前我们的ClientForm并没有nickname，但是注册email用户的时候是需要的，所以我们建立一个UserEmailForm继承ClientForm完成他自己的业务<br>不能从request.json 中拿，因为这个参数没经过校验<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">from wtforms import Form, StringField, IntegerField ,ValidationError    # 字符串类型,数字类型,异常</span><br><span class="line">from wtforms.validators import DataRequired, length,  Email, Regexp</span><br><span class="line">from app.libs.enums import ClientTypeEnum</span><br><span class="line">from app.models.user import User</span><br><span class="line"></span><br><span class="line"># 构建client验证器</span><br><span class="line">class ClientForm(Form):</span><br><span class="line">    account = StringField(validators=[DataRequired(), length(min=1, max=32)])</span><br><span class="line">    secret = StringField()   # 由于客户端类型的不同，密码不一定要传入</span><br><span class="line">    type = IntegerField(validators=[DataRequired()])</span><br><span class="line"></span><br><span class="line">    # 验证client_type</span><br><span class="line">    def validate_type(self, value):</span><br><span class="line">        try:</span><br><span class="line">        # 将用户传来的参数去枚举类中匹配，如果匹配失败，则抛出异常</span><br><span class="line">        # 如果匹配成功则将int转换成枚举</span><br><span class="line">            client = ClientTypeEnum(value.data)  # value.data 取到值</span><br><span class="line">        except ValueError as e:</span><br><span class="line">            raise e</span><br><span class="line">    # 面向对象的继承特性，减少代码量，ClientForm是很有必要存在的</span><br><span class="line">        self.type = client  # 将枚举赋值给 type</span><br><span class="line"></span><br><span class="line">class UserEmailForm(ClientForm):</span><br><span class="line">    account = StringField(validators=[</span><br><span class="line">        Email(message=&apos;validate email&apos;)</span><br><span class="line">        ])  # 必须是Email</span><br><span class="line">    secret = StringField(validators=[</span><br><span class="line">        DataRequired(),</span><br><span class="line">        Regexp(r&apos;^[A-Za-z0-9_*&amp;$#@]&#123;6,22&#125;$&apos;)</span><br><span class="line">        ]) #必须要密码，密码格式 </span><br><span class="line">    nickname = StringField(validators=[DataRequired(),</span><br><span class="line">                                       length(min=2, max=22)])  # 新增一个个性化参数nickname</span><br><span class="line"></span><br><span class="line">    def validate_account(self, value):   # 验证账号是否已经注册</span><br><span class="line">        if User.query.filter_by(email=value.data).first():  # 如果能查询到email</span><br><span class="line">            raise ValidationError()   # 则抛出异常</span><br></pre></td></tr></table></figure></p>
<p>完成视图函数的编写<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">from app.libs.redprint import Redprint</span><br><span class="line"></span><br><span class="line">from app.validators.forms import ClientForm,UserEmailForm</span><br><span class="line">from flask import request</span><br><span class="line">from app.libs.enums import ClientTypeEnum</span><br><span class="line">from app.models.user import User</span><br><span class="line"></span><br><span class="line">api = Redprint(&apos;client&apos;)  # 实例化一个Redprint</span><br><span class="line"></span><br><span class="line">@api.route(&apos;/register&apos;, methods = [&apos;POST&apos;] )  # 路由注册  # 因为这里把POST打成PSOT，导致不能使用POST访问，状态码405</span><br><span class="line">def create_client():                         </span><br><span class="line">    # 表单 - 一般网页  json - 一般移动端</span><br><span class="line">    # 注册 登录</span><br><span class="line">    # 参数 校验  接收参数</span><br><span class="line">    # WTForms 验证表单</span><br><span class="line"></span><br><span class="line">#用来接收json类型的参数</span><br><span class="line">    data = request.json</span><br><span class="line"># 关键字参数data是wtform中用来接收json参数的方法</span><br><span class="line">    form = ClientForm(data = data)  # data =   来接收json</span><br><span class="line"></span><br><span class="line">    if form.validate():</span><br><span class="line"># 替代switchcase-&#123;Enum_name:handle_func&#125;</span><br><span class="line">        promise = &#123;</span><br><span class="line">            ClientTypeEnum.USER_EMAIL: __register_user_by_email#,</span><br><span class="line">            # ClientTypeEnum.USER_MINA: __register_user_by_MINA   # 可在此处构建多种枚举类型</span><br><span class="line">        &#125;</span><br><span class="line">        promise[form.type.data]()</span><br><span class="line">    return &apos;sucess&apos;  #  暂时返回sucess</span><br><span class="line">#总 ↑</span><br><span class="line"></span><br><span class="line">#分 ↓</span><br><span class="line"></span><br><span class="line">def __register_user_by_email():</span><br><span class="line">    form = UserEmailForm(data=request.json)</span><br><span class="line">    if form.validate():</span><br><span class="line">        User.register_by_email(form.nickname.data,</span><br><span class="line">                               form.account.data,</span><br><span class="line">                               form.secret.data)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># def __register_user_by_MINA():</span><br><span class="line">#     pass</span><br></pre></td></tr></table></figure></p>
<p>create_client和__register_user_by_email是一个总-分的关系，客户端注册的种类是比较多的，但是这些众多的种类又有一些共通的东西，比如处理客户端的type的值，就是所有的客户端都要携带的参数。对于这些共有的参数，我们就统一在create_client,ClientForm中进行处理<br> 对于不同的客户端的特色的属性和功能，我们放在“分”里面来，比如email的nikename</p>
<p>3.3 重构代码-自定义验证对象<br>我们之前写的代码，有一些细节问题。</p>
<p>1.传入错误的参数，虽然没有添加到数据库，但是返回 结果显示正常<br>这是因为，form.validate()如果校验不通过，他不会抛出异常，而是会将异常信息存储在form对象中。<br> 所以这个时候我们应该判断如果校验不通过，就抛出一个自定义的异常。</p>
<p> <strong>比如我之前在”type” = “100”,错误，但还是会return sucess。</strong></p>
<p>werkzeug为我们提供的大量的异常，都继承自HTTPException，但是这些异常都很具体，不能为我们所用。不过我们可以自己定义一个异常来继承HTTPException</p>
<p>2.自定义异常<br>rest中状态码代表的意义<br>400 参数错误<br>401 未授权<br>403 禁止访问<br>404 没有找到资源或者页面<br>500 服务器未知错误<br>200 查询成功<br>201 更新/创建成功<br>204 删除成功<br>301/302 重定向</p>
<p>app\libs\erro_code.py<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">from werkzeug.exceptions import HTTPException</span><br><span class="line"># 自定义异常类</span><br><span class="line"></span><br><span class="line">class ClientTypeErro(HTTPException):</span><br><span class="line">    code = 400</span><br><span class="line">    description = (</span><br><span class="line">        &apos;client is invalid&apos;</span><br><span class="line">    )</span><br></pre></td></tr></table></figure></p>
<p>修改后的试图函数<br>app\api\v1\client.py<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">from app.libs.redprint import Redprint</span><br><span class="line"></span><br><span class="line">from app.validators.forms import ClientForm,UserEmailForm</span><br><span class="line">from flask import request</span><br><span class="line">from app.libs.enums import ClientTypeEnum</span><br><span class="line">from app.models.user import User</span><br><span class="line"></span><br><span class="line"># from werkzeug.exceptions import HTTPException   #  异常</span><br><span class="line">from app.libs.erro_code import ClientTypeErro   # 导入自定义异常</span><br><span class="line"></span><br><span class="line">api = Redprint(&apos;client&apos;)  # 实例化一个Redprint</span><br><span class="line"></span><br><span class="line">@api.route(&apos;/register&apos;, methods = [&apos;POST&apos;] )  # 路由注册  # 因为这里把POST打成PSOT，导致不能使用POST访问，状态码405</span><br><span class="line">def create_client():                         </span><br><span class="line">    # 表单 - 一般网页  json - 一般移动端</span><br><span class="line">    # 注册 登录</span><br><span class="line">    # 参数 校验  接收参数</span><br><span class="line">    # WTForms 验证表单</span><br><span class="line"></span><br><span class="line">#用来接收json类型的参数</span><br><span class="line">    data = request.json</span><br><span class="line"># 关键字参数data是wtform中用来接收json参数的方法</span><br><span class="line">    form = ClientForm(data = data)  # data =   来接收json</span><br><span class="line"></span><br><span class="line">    if form.validate():</span><br><span class="line"># 替代switchcase-&#123;Enum_name:handle_func&#125;</span><br><span class="line">        promise = &#123;</span><br><span class="line">            ClientTypeEnum.USER_EMAIL: __register_user_by_email#,</span><br><span class="line">            # ClientTypeEnum.USER_MINA: __register_user_by_MINA   # 可在此处构建多种枚举类型</span><br><span class="line">        &#125;</span><br><span class="line">        promise[form.type.data]()</span><br><span class="line">    else:</span><br><span class="line">        raise ClientTypeErro()  # 抛出自定义异常</span><br><span class="line">    return &apos;sucess&apos;  #  暂时返回sucess</span><br><span class="line">#总 ↑</span><br><span class="line"></span><br><span class="line">#分 ↓</span><br><span class="line"></span><br><span class="line">def __register_user_by_email():</span><br><span class="line">    form = UserEmailForm(data=request.json)</span><br><span class="line">    if form.validate():</span><br><span class="line">        User.register_by_email(form.nickname.data,</span><br><span class="line">                               form.account.data,</span><br><span class="line">                               form.secret.data)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># def __register_user_by_MINA():</span><br><span class="line">#     pass</span><br></pre></td></tr></table></figure></p>
<p>修改完成之后，已经修复了之前的缺陷，但是这样爆出了两个问题：<br> 1.代码太啰嗦了，每个试图函数里，都需要这么写<br> 2.ClientTypeError只是代表客户端类型异常，其他的参数校验不通过也抛出这个异常的话不合适</p>
<p>2.异常返回的标准与重要性<br>我们的restapi返回的信息主要分为以下三类:<br> 1.页数数据信息<br> 2.操作成功提示信息<br> 3.错误异常信息</p>
<p>如果错误异常信息不够标准，那么客户端很难去处理我们的错误异常。</p>
<p>无论上面三种，都属于输出，REST-API要求输入输出都要返回JSON</p>
<p>3.自定义ApiException<br>通过分析HttpException的get_body,get_header源码我们可以知道，这两个方法分别组成了默认异常页面的header和html文本，所以如果要让我们的异常返回json格式的信息，需要继承HttpException并重写这两个方法.  <strong>万不得已,不要动框架源代码</strong><br> HttpException 源代码部分<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">class HTTPException(Exception):</span><br><span class="line"></span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    Baseclass for all HTTP exceptions.  This exception can be called as WSGI</span><br><span class="line">    application to render a default error page or you can catch the subclasses</span><br><span class="line">    of it independently and render nicer error messages.</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line"></span><br><span class="line">    code = None</span><br><span class="line">    description = None</span><br><span class="line"></span><br><span class="line">    def __init__(self, description=None, response=None):</span><br><span class="line">        Exception.__init__(self)</span><br><span class="line">        if description is not None:</span><br><span class="line">            self.description = description</span><br><span class="line">        self.response = response</span><br><span class="line"></span><br><span class="line">    def get_body(self, environ=None):</span><br><span class="line">        &quot;&quot;&quot;Get the HTML body.&quot;&quot;&quot;</span><br><span class="line">        return text_type((</span><br><span class="line">            u&apos;&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 3.2 Final//EN&quot;&gt;\n&apos;</span><br><span class="line">            u&apos;&lt;title&gt;%(code)s %(name)s&lt;/title&gt;\n&apos;</span><br><span class="line">            u&apos;&lt;h1&gt;%(name)s&lt;/h1&gt;\n&apos;</span><br><span class="line">            u&apos;%(description)s\n&apos;</span><br><span class="line">        ) % &#123;</span><br><span class="line">            &apos;code&apos;:         self.code,</span><br><span class="line">            &apos;name&apos;:         escape(self.name),</span><br><span class="line">            &apos;description&apos;:  self.get_description(environ)</span><br><span class="line">        &#125;)</span><br><span class="line"></span><br><span class="line">    def get_headers(self, environ=None):</span><br><span class="line">        &quot;&quot;&quot;Get a list of headers.&quot;&quot;&quot;</span><br><span class="line">        return [(&apos;Content-Type&apos;, &apos;text/html&apos;)]</span><br></pre></td></tr></table></figure></p>
<p>app\libs\erro.py<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">from werkzeug.exceptions import HTTPException</span><br><span class="line">from flask import request,json</span><br><span class="line"></span><br><span class="line"># 重写 HTTPException</span><br><span class="line"></span><br><span class="line">class APIException(HTTPException):</span><br><span class="line">    # 定义默认异常信息</span><br><span class="line">    code = 500</span><br><span class="line">    msg = &apos;sorry, we make a mistake&apos;</span><br><span class="line">    erro_code = 999     # 自定义的错误码   # 建议新建一个code.md记录自定义的错误码</span><br><span class="line"></span><br><span class="line">    def __init__(self, msg = None, code = None, erro_code = None,</span><br><span class="line">                headers = None):   # 给定None ,不传就是默认值</span><br><span class="line"></span><br><span class="line">        # 传了的话，就是选传的值</span><br><span class="line">        if code:</span><br><span class="line">            self.code = code</span><br><span class="line">        if erro_code:</span><br><span class="line">            self.erro_code = erro_code</span><br><span class="line">        if msg:</span><br><span class="line">            self.msg = msg   </span><br><span class="line">        super(APIException, self).__init__(self.msg, None)   # 继承</span><br><span class="line"></span><br><span class="line">    def get_body(self, environ=None):</span><br><span class="line">        body = dict(</span><br><span class="line">            msg = self.msg,</span><br><span class="line">            erro_code = self.erro_code,</span><br><span class="line">            # request = &apos;POST v1/client/register&apos;</span><br><span class="line">            request = request.method+&apos; &apos;+self.get_url_no_param() </span><br><span class="line">        )       </span><br><span class="line">        text = json.dumps(body)  # 将字典转换为json 文本  json 序列化</span><br><span class="line">        return text</span><br><span class="line"></span><br><span class="line">    def get_headers(self, environ=None):</span><br><span class="line">        return [(&apos;Content-Type&apos;, &apos;application/json&apos;)]  # 将返回标识成json</span><br><span class="line"></span><br><span class="line">    @staticmethod</span><br><span class="line">    def get_url_no_param():  # 没有？后面的参数</span><br><span class="line">        full_path = request.full_path  # 拿到 url完整路径</span><br><span class="line">        main_path = full_path.split(&apos;?&apos;) # 去掉？和后面</span><br><span class="line">        return main_path[0]</span><br></pre></td></tr></table></figure></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/flask-api/Flask构建可扩展的RESTful-API-4--理解WTForms并灵活改造她/" rel="next" title="Flask构建可扩展的RESTful-API-4--理解WTForms并灵活改造她">
                <i class="fa fa-chevron-left"></i> Flask构建可扩展的RESTful-API-4--理解WTForms并灵活改造她
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/flask-api/Flask构建可扩展的RESTful-API-2--REST基本特征/" rel="prev" title="Flask构建可扩展的RESTful-API-2--REST基本特征">
                Flask构建可扩展的RESTful-API-2--REST基本特征 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.png" alt="WeiLai">
            
              <p class="site-author-name" itemprop="name">WeiLai</p>
              <p class="site-description motion-element" itemprop="description">好学近乎知，力行近乎仁，知耻近乎勇</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">132</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/itswl" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:imwl@live.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/6aa4c1b2a4a4" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-book"></i>简书</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.facebook.com/profile.php?id=100021764796181" target="_blank" title="Facebook">
                      
                        <i class="fa fa-fw fa-facebook"></i>Facebook</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#3-1-关于用户的思考"><span class="nav-number">1.</span> <span class="nav-text">3.1 关于用户的思考</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">WeiLai</span>

  
</div>


  <!--<div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>

-->



        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

  
</body>
</html>
